﻿using QDAS;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;

namespace QDasConverter.Core
{
    public class C2021T07_HoutaConsole : ConvertBase
    {
        string configFile = @"./configs/C2021T03_CTL_Properties.csv";
        DateTime lastConvertTime = DateTime.Now;

        public C2021T07_HoutaConsole()
        {
            NeedConnectionCheck = false;
            DisplayName = "霍塔终检台转换器";
            Version = "alpha1 Released Date: 2022/04/03 Inner Name: C2021T07_HoutaConsole";
        }

        // 保证一直转换。
        public override bool NeedConvert() => true;

        public override bool OnStart()
        {
            if (DebugMode)
            {

            }

            return base.OnStart();
        }

        public override void OneLoop_Prepare()
        { 
            
        }

        public override void OneLoop_Process()
        {
            var xmlfile = @"..\..\samples\HouTaConsole\DF727A56-Gear 1 Coast-20220120 173048025.xml";

            if (!File.Exists(xmlfile))
            {
                Console.WriteLine($"Xml file does not exist: {xmlfile}.");
                return;
            }
            try
            {
                ProcessDirectory(xmlfile);
            }catch (Exception ex)
            {
                AddLog(LogType.Error, ex.Message);
            }

            Thread.Sleep(100);
        }

        public string GetNodeText(XmlNode node, string path)
        {
            var n = node.SelectSingleNode(path);
            return n ==  null ? "" : n.InnerText;
        }

        private void ProcessDirectory(string xmlfile)
        {
            XmlDocument root = new XmlDocument();
            root.Load(xmlfile);


            var TestIem = root.SelectSingleNode("/NVH2XML/TestItem");
            var TestBenchId = TestIem.SelectSingleNode("TestBenchId").InnerText;  // 检测台架的编号
            var K1001 = TestIem.SelectSingleNode("TestItemName").InnerText; // 箱体的版本（型号）
            var K1003 = "终检";
            var K1206 = "霍塔终检台";
            var K0014 = TestIem.SelectSingleNode("SerialNumber").InnerText; // 箱体的编码

            var Loadstep = root.SelectSingleNode("/NVH2XML/TestItem/Loadsteps/Loadstep");
            var K0004 = Loadstep.SelectSingleNode("StartTime").InnerText;


            QFile qf = new QFile();
            qf[1001] = K1001;
            qf[1002] = K1001;
            qf[1003] = K1003;
            qf[1206] = K1206;


            // 被测参数与测量值
            var LineRangeDefinition = root.SelectNodes("//LineRangeDefinition");
            foreach (XmlNode node in LineRangeDefinition)
            {
                /* LineRangeDefinition 测量信息
                   Name：测量项目，如1st Gear H1 （对应文件霍塔EOL-NVH下线检测技术要求中名称）
                   From：设定值 如 14
                   QI：测试结果，如 30
                   UpperThreshold：上限百分比，如 0.87
                   测量值：等于 QI*UpperThrehold， 如 30 * 0.87 = 26.1, 若QI得值小于100即合格。
                 */
                var K2001 = node.SelectSingleNode("Name").InnerText;
                var K2110 = "0";
                var K2111 = GetNodeText(node, "From");
                K2111 = K2111.Length == 0 ? "0" : K2111;

                var QI = float.Parse(node.SelectSingleNode("QI").InnerText);
                var UpperThreshold = float.Parse(node.SelectSingleNode("UpperThreshold").InnerText);
                var K0001 = (QI*UpperThreshold).ToString();

                var qc = qf.AddQCharacteristic();
                qc[2001] = K2001;
                qc[2110] = K2110;
                qc[2111] = K2111;

                var qdi = qc.AddItem();
                qdi.date = DateTime.Now;
                qdi[0014] = K0014;
                qdi.SetValue(K0001);
            }
            qf.ToDMode();
            
            SaveToDFQ(qf, Path.Combine(OutputDirectory, $"C7_HoutaConsole_{NowString()}.dfq"));
        }

        public override void OneLoop_Completed()
        {
            ia.WriteValue("lastConvertTime", lastConvertTime.ToString("yyyy-MM-dd HH:mm:ss"));
        }

    }
}
